import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'

// 定义路由元数据类型
declare module 'vue-router' {
  interface RouteMeta {
    title?: string
    requiresAuth?: boolean
    role?: 'admin' | 'tourist' | string[]
  }
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('../views/LayoutView.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          redirect: '/welcome',
        },
        {
          path: '/welcome',
          name: 'welcome',
          component: () => import('../views/WelcomeView.vue'),
          meta: { title: '欢迎页面' },
        },

        {
          path: '/visitor',
          name: 'visitor',
          component: () => import('../views/VisitorView.vue'),
          meta: { title: '游客页面', role: 'tourist' },
        },
        // 学生相关页面已移除
        {
          path: '/heritage-protection',
          name: 'heritage-protection',
          component: () => import('../views/HeritageProtectionView.vue'),
          meta: { title: '文化遗产保护意识' },
        },
        {
          path: '/report-behavior',
          name: 'report-behavior',
          component: () => import('../views/ReportBehaviorView.vue'),
          meta: { title: '不文明行为举报' },
        },
        {
          path: '/protection-tips',
          name: 'protection-tips',
          component: () => import('../views/ProtectionTipsView.vue'),
          meta: { title: '文物保护小贴士' },
        },
        {
          path: '/feature-management',
          name: 'feature-management',
          component: () => import('../views/FeatureManagementView.vue'),
          meta: { title: '地理要素管理', role: 'admin' },
        },
        {
          path: '/behavior-management',
          name: 'behavior-management',
          component: () => import('../views/UncivilizedBehaviorManagementView.vue'),
          meta: { title: '不文明行为管理', role: 'admin' },
        },
      ],
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { title: '登录' },
    },
  ],
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()

  // 设置页面标题
  document.title = `${to.meta.title || '北京旅游系统'}`

  // 检查是否需要登录权限
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    // 检查是否已登录
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      next({ name: 'login' })
      return
    }

    // 检查角色权限
    if (to.meta.role && !userStore.hasPermission(to.meta.role)) {
      ElMessage.error('您没有权限访问该页面')
      next({ name: 'welcome' })
      return
    }
  }

  // 如果已登录且访问登录页，重定向到首页
  if (to.path === '/login' && userStore.isLoggedIn) {
    next({ path: '/' })
    return
  }

  next()
})

export default router
